<template>
	<gui-page ref="guiPage" :customHeader="true">
		<template v-slot:gHeader>
			<nav-bar-custom left-icon="left" :leftType="'1'" @clickLeftBack="clickLeftBack"
				:title="$t('consumo.salesOutboundReturn')" @clickRight="clickRight" scanType="1"></nav-bar-custom>
		</template>
		<template v-slot:gBody>
			<view class="page-auto-noheight paddingbottom">
				<!-- 调拨单信息 -->
				<view class="custom-form-card">
					<view class="custom-card-title">
						<text class="title-line"></text>
						{{ $t('distributedOut.informationOut') }}
					</view>
					<view class="custom-card-itemOne">
						<text class="item-info-title">{{ $t('smashRemoval.letterOfAdvice') }}：</text>{{data.enterDetails.dnCode }}
					</view>
					<view class="custom-card-itemOne">
						<view class="card-item-50" style="width: 100%;">
							<text class="item-info-title">{{ $t('translationImage.documentationDate') }}：</text>{{data.enterDetails.dnDate }}
						</view>
					</view>
					<view class="custom-card-itemOne">
						<view class="card-item-50">
							<text class="item-info-title">{{ $t('distributedEnter.compiler') }}：</text>{{data.enterDetails.createUserName}}
						</view>
					</view>
					<view class="custom-card-itemOne">
						<view class="card-item-50">
							<text class="item-info-title">{{ $t('smashRemoval.quantityDelivered') }}：</text>{{data.enterDetails.sumScan }}
						</view>
						<view class="card-item-50">
							<text class="item-info-title">{{ $t('smashRemoval.quantityNotDelivered') }}：</text>{{data.enterDetails.sumQty- data.enterDetails.sumScan }}
						</view>
					</view>
					<view class="custom-card-itemOne">
						<text class="item-info-title">{{ $t('smashRemoval.deliveredTotal') }}：</text>{{data.enterDetails.sumQty }}
					</view>
					<view class="custom-card-itemOne">
						<text class="item-info-title">{{ $t('pageTranslation.scannedTotalQty') }}：</text>{{data.enterDetails.currentScanNum|| 0 }}
					</view>
				</view>
				<!-- 扫描条码 -->
				<view class="custom-form-card">
					<view class="custom-card-title">
						<text class="title-line"></text>
						{{ $t('distributedEnter.barcodeScan') }}
					</view>
					<view class="custom-card-scan" style="margin-top:20rpx;">
						<uni-easyinput class="uni-mt-5" suffixIcon="scan" v-model="data.barcode"
							:placeholder="$t('stockManage.pleaseScanCode')" type="search" @confirm="confirm"
							@iconClick="iconClick">
						</uni-easyinput>
					</view>
				</view>
				<!-- 当前扫描条码 -->
				<view v-if="data.scanInfo" class="custom-form-card">
					<uni-collapse v-model="data.value">
						<uni-collapse-item titleBorder="none" :show-animation="true">
							<template v-slot:title>
								<view class="custom-card-title">
									<text class="title-line"></text> {{ $t('distributedOut.atPresent') }}
								</view>
							</template>
							<view class="content">
								<view class="custom-card-itemOne">
									<text class="item-info-title">{{ $t('distributedEnter.materialCode') }}：</text>{{
										data.scanInfo.materialCode }}
								</view>
								<view class="custom-card-itemOne">
									<text class="item-info-title">{{ $t('distributedEnter.materialName') }}：</text>{{
										data.scanInfo.materialName }}
								</view>
								<view class="custom-card-itemOne">
									<view class="card-item-50">
										<text class="item-info-title">{{ $t('distributedEnter.uom') }}：</text>{{
											data.scanInfo.unit }}
									</view>
									<view class="card-item-50">
										<text class="item-info-title">{{ $t('pageTranslation.qtyOfDelivery') }}：</text>
										{{ data.scanInfo.currentQty }}
									</view>
								</view>
							</view>
						</uni-collapse-item>
					</uni-collapse>
				</view>
				<view class="gui-flex gui-rows gui-nowrap gui-align-items-center gui-margin-top">
					<view class="gui-title-line"></view>
					<text class="gui-primary-text gui-h6" style="padding-left:50rpx; padding-right:50rpx;">{{
						$t('smashRemoval.salesOrderNo') }}：{{ data.salesOrders }}</text>
					<view class="gui-title-line"></view>
				</view>
				<uni-card class="element-auto gui-margin-top card-my">
					<view class="element-auto" style="height: 300rpx">
						<zb-table :columns="data.column1" :stripe="true" :border="true" :data="tableData.list"
							@customLook="customBtnFn" @rowClick="recommendClick" :cell-style="cellStyle"
							:cell-header-style="cellHeaderStyle">
						</zb-table>
					</view>
				</uni-card>
				<view style="height: 150rpx;"></view>
				<!-- 底部操作栏 -->
				<view class="page-bottom-box bottom-postion">
					<view class="page-bottomBtn bottomBtn-bgcolor-green" @click="submit">
						{{ $t('calendar.submit') }}
					</view>
				</view>
			</view>
			<!-- 普通弹窗 -->
			<uni-popup ref="popup" type="center">
				<view class="input-dialog-box"
					style="padding: 40rpx 20rpx 20rpx 20rpx;border-radius: 22rpx;width: 600rpx;">
					<uni-icons class="popup-close-icons" type="closeempty" color="#9C9C9C" size="26"
						@click="closePopup"></uni-icons>
					<view class="custom-card-itemOne">
						<text class="item-info-title">{{ $t('distributedEnter.materialCode') }}：</text>{{
							data.popupInfo.materialCode }}
					</view>
					<view class="custom-card-itemOne">
						<text class="item-info-title">{{ $t('distributedEnter.materialName') }}：</text>{{
							data.popupInfo.materialName }}
					</view>
					<view class="custom-card-itemOne flex-start">
						<view class="item-info-title">{{ $t('distributedEnter.materialSpec') }}：</view>
						<view class="specview">{{ data.popupInfo.spec }}</view>
					</view>

					<view class="custom-card-itemOne">
						<text class="item-info-title">{{ $t('distributedEnter.uom') }}：</text>{{ data.popupInfo.saleUnit
						}}
					</view>
					<view class="custom-card-itemOne">
						<text class="item-info-title">{{ $t('distributedEnter.sumScanQty') }}：</text>{{
							data.popupInfo.scanQty }}
					</view>
					<view class="custom-card-itemOne">
						<text class="item-info-title">{{ $t('distributedEnter.overallQty') }}：</text>{{
							data.popupInfo.saleQty }}
					</view>
					<view class="custom-card-itemOne">
						<text class="item-info-title">{{ $t('distributedEnter.scannedQuantity') }}：</text>{{
							data.popupInfo.scanNum
						}}
					</view>
				</view>
			</uni-popup>
		</template>
	</gui-page>
</template>

<script setup>
import {
	navigate,
	navigateBack
} from '@/utils/routerSkip.js';
import {
	reactive,
	ref,
	onMounted,
	computed,
	watch,
	toRaw
} from 'vue';
import {
	findWmsDnHById,
	sdistributedCallOut,
	selectWmsBarcodeInfoWms,
	salesLocation,
	checkBarcodeTime
} from '@/api/api.js'
import tableColor from '@/hooks/tableColor.js'
import storageBin from '@/components/storageBin.vue'
import {
	useStore
} from "vuex";
import pdaScan from '@/hooks/pdaScan.js'
import {
	basPdaOperationLogFn
} from '@/utils/index.js';
import {
	OPERATION_COMMIT,
	OPERATION_LOOK,
	OPERATION_SCAN
} from '@/constant/index.js'
//JS国际化引入
import {
	useI18n
} from 'vue-i18n';
import {
	onBackPress
} from '@dcloudio/uni-app';
import { parse } from 'psl';
const {
	t
} = useI18n();

let store = useStore()
const {
	scan
} = pdaScan()
components: {
	storageBin
}
let {
	tableData
} = tableColor();
const {
	cellStyle,
	cellHeaderStyle
} = tableColor();
const props = defineProps({
	id: String,
	salesOrders: String,
})
let popup = ref(null)
let popupRecommend = ref(null)

let data = reactive({
	id: props.id, // 上级界面传过来的id
	salesOrders: props.salesOrders, // 销售订单号
	list: [],
	scanInfo: undefined,
	value: ['0'],
	selectedText: '',
	selectId: '',
	organizationEnterList: [],
	locationId: '',
	currentLocationInfo: {}, //当前选中库位信息
	barcode: '',
	column1: [{
		name: 'age',
		type: 'ailibtn',
		label: t('translationImage.operation'),
		scanValue: '',
		fixed: true,
		width: 80,
	},
	{
		name: 'materialCode',
		label: t('distributedEnter.materialCode'),
		fixed: true,
		width: 100,
		sorter: false,
		emptyString: '--'
	},
	{
		name: 'materialName',
		label: t('distributedEnter.materialName'),
	},
	// {
	// 	name: 'location',
	// 	label: t('warehousing.recommendLocation'),
	// },
	{
		name: 'spec',
		label: t('distributedEnter.materialSpec'),
	},
	{
		name: 'saleUnit',
		label: t('distributedEnter.uom'),
		width: 60,
	},
	{
		name: 'saleQty',
		label: t('distributedEnter.overallQty'),
		width: 60,
	},
	//已发货数量
	{
		name: 'scanQty',
		label: t('distributedEnter.sumScanQty'),
		width: 120,
	},
	{
		name: 'scanNum',
		label: t('distributedEnter.scannedQuantity'),
		width: 120,
	}
	],
	requestParam: {
		warehouseCode: 'RM'
	},
	ignoreLocationCode: [], //前端算满的库位
	enterDetails: {},
	currentBarcode: {}, //当前barcode
	locationUseList: [], //当前用户使用库位情况
	popupInfo: {}, //当前行的弹窗信息
	recommend: {},
	doubleArray: {}, //物料纬度的barcode条码
	recommendData: [], //推荐的库位
	recommendCurrent: '' //当前推荐的要扫描的库位
})
onMounted(() => {
	uni.$on('scancodedate', (res) => {
		console.log('获取到的code：' + res.code)
		getCode(res.code, 'pda')
	})
	findStepoutHByIdFn()
})
data.barcodeList = computed(() => {
	return store.state.stockRemovalReturnList
})

onBackPress((options) => {
	if (options.from == 'backbutton') {
		navBackCheck()
		return true;
	}
})
//导航栏左侧返回
const clickLeftBack = () => {
	navBackCheck()
}
const navBackCheck = () => {
	if (!data.barcodeList.length) {
		uni.navigateBack({
			delta: 1
		});
		return true
	}
	uni.showModal({
		title: t('smashRemoval.warmPrompt'),
		content: t('materials.unsubmittedDataIn'),
		success: function (res) {
			if (res.confirm) {
				store.commit('reactStockRemovalReturnList')
				uni.navigateBack({
					delta: 1
				});
			} else if (res.cancel) {
				console.log('用户点击取消');
			}
		}
	});
	return true
}

// 剥离计算方法 用于方便调用
const watcShowscanList = (newVal) => {
	// 第一次判断  判断当前数组是否有值
	let tepData = toRaw(newVal)
	if (!tepData.length) {
		data.scanInfo = undefined
	}
	let currentScanNum = tepData.reduce(function (prev, cur) {
		return prev + Number(cur.scanNum);
	}, 0)
	// 遍历数组 查询当前扫描的物料信息 与当前的收集单信息相比对进行重新赋值
	tableData.list.forEach(element => {
		let scanNum = 0
		tepData.forEach(item => {
			// 根据当前扫描的materialCode物料code  查询到相对应收集单信息
			if (element.materialCode == item.materialCode) {
				scanNum = scanNum + Number(item.scanNum)
			}
		});
		element.scanNum = scanNum //物料数量
	});

	data.enterDetails.currentScanNum = currentScanNum
}
//监听
watch(() => data.barcodeList, (newVal, oldVal) => {
	console.log(newVal)
	for (var j = 0; j < data.recommendData.length; j++) {
		data.recommendData[j].scanQty = 0;  //全部置为一个没有扫
	}
	if (newVal.length) {
		for (var i = 0; i < newVal.length; i++) {
			var lcode = newVal[i].locationCode //库位
			var qty = newVal[i].currentQty

			if (!data.recommendData.some(m => m.lcode == lcode)) //不存在这个库位
			{
				//这里说明库位发生了变化
				// data.recommendData.push({lcode:lcode,qty:qty})
			} else {
				for (var j = 0; j < data.recommendData.length; j++) {
					if (data.recommendData[j].lcode == lcode) {
						var q = parseInt(qty);
						data.recommendData[j].scanQty += q;
					}
				}
			}
		}
	} else {
		for (var j = 0; j < data.recommendData.length; j++) {
			data.recommendData[j].scanQty = 0;  //全部置为一个没有扫
		}
	}
	console.log(data.recommendData)
	var cu = data.recommendData.filter(e => e.qty > e.scanQty)
	if (cu.length) {
		data.recommendCurrent = cu[0].lcode
	}
	else {
		data.recommendCurrent = ' '
	}
	//这里重新计算推荐库位
	watcShowscanList(newVal)
}, {
	immediate: true,
	deep: true
});
// 提交
const submit = () => {
	console.log('提交')
	if (!data.barcodeList.length) {
		uni.showToast({
			title: t('pageTranslation.plsScanThe'),
			icon: 'none'
		})
		return
	}
	let barcodes = []
	data.barcodeList.forEach(element => {
		barcodes.push({
			barcode: element.barcode,
			id: element.id,
			materialCode: element.materialCode,
			currentQty: element.currentQty,
			warehouseCode: element.warehouseCode,
			locationCode: element.locationCode
		})
	});
	let parmes = {
		dnHId: props.id,
		dnTypeCode: 'ts',
		sourceBillCode: data.enterDetails.dnCode,
		soCode: data.salesOrders,
		barcodes: barcodes
	}
	sdistributedCallOut(parmes).then(res => {
		try {
			let inputParameter = JSON.stringify(parmes)
			let returnParameter = JSON.stringify(res)
			let operationPicture = '销售出库退货'
			let callInterface = res.rquestUrl
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode: res.status, //返回状态
				errorMessage: res.message, //错误信息
				isPass: res.status == 200 ? 'Y' : 'N', //是否成功 Y N
				operationType: OPERATION_COMMIT
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) { }
		if (res.status == 200) {
			uni.showToast({
				title: t('smashRemoval.submitSuccessfully'),
				icon: 'none',
				duration: 2000,
				complete: () => {
					// navigateBack()
					store.commit('reactStockRemovalReturnList')
					// 返还上一个页面
					setTimeout(() => {
						navigateBack()
					}, 1000)

					// 重新刷新当前界面
					// findStepoutHByIdFn()
				}
			})
		} else {
			uni.showModal({

				content: res.message,

			});
		}
	})
}
// 获取code
const getCode = (code, type) => {
	// 判断这个托盘本次有没有绑定过
	let isBind = data.barcodeList.filter(x => x.barcode == code);
	if (isBind.length) {
		uni.showToast({
			title: t('JsInternational.scanned'),
			icon: 'none'
		})
		return
	}
	if (!code) {
		uni.showToast({
			title: t('stockManage.pleaseScanCode'),
			icon: 'none'
		})
		return
	}
	let tepData = toRaw(data.barcodeList)

	let allScanNum = tepData.reduce(function (prev, cur) {
		return prev + Number(cur.scanNum);
	}, 0)
	if (allScanNum > Number(data.enterDetails.sumQty)) {
		uni.showToast({
			title: t('JsInternational.scanningBeyond'),
			icon: 'none'
		})
		return
	}
	let parmes = {
		receiptId: data.id,
		asnHId: data.id,
		barcode: code,
		selectType: 'salesOut',
		dnTypeCode: 'ts',
	}
	selectWmsBarcodeInfoWms(parmes).then(res => {
		try {
			let inputParameter = JSON.stringify(parmes)
			let returnParameter = JSON.stringify(res)
			let operationPicture = '销售出库退货'
			let callInterface = res.rquestUrl
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode: res.status, //返回状态
				errorMessage: res.message, //错误信息
				isPass: res.status == 200 ? 'Y' : 'N', //是否成功 Y N
				operationType: OPERATION_SCAN
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) { }
		console.log(res)
		if (res.status == 200) {
			let bool = tableData.list.some((item) => {
				return item.materialCode == res.data.materialCode
			})
			if (!bool) {
				uni.showToast({
					title: t('materials.materialIsNot'),
					icon: "none"
				});
				return
			}

			data.scanInfo = res.data
			data.scanInfo.scanNum = res.data.currentQty
			store.commit('addStockRemovalReturnList', data.scanInfo)
		} else {
			uni.showToast({
				title: res.message,
				icon: 'none'
			})
		}
	})

}
// 用户点击扫码图标
const iconClick = async (type) => {
	if (type === 'suffix') {
		let code = await scan()
		getCode(code, 'scan')
	}
}
// 用户点击搜索
const confirm = () => {
	getCode(data.barcode, 'keydown')
}
// 根据id查询调入单详情
const findStepoutHByIdFn = () => {
	let parmes = {
		id: props.id
	}
	findWmsDnHById(parmes).then(res => {
		try {
			let inputParameter = JSON.stringify(parmes)
			let returnParameter = JSON.stringify(res)
			let operationPicture = '销售出库'
			let callInterface = res.rquestUrl
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode: res.status, //返回状态
				errorMessage: res.message, //错误信息
				isPass: res.status == 200 ? 'Y' : 'N', //是否成功 Y N
				operationType: OPERATION_LOOK
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) { }
		if (res.status == 200) {
			data.enterDetails = res.data;
			data.enterDetails.currentScanNum = res.data.sumScan;
			tableData.list = res.data.wmsDnDS;
			// // 推荐库位  获取调用
			// data.recommend = res.data.wmsDnDS;
			// let arr = [];
			// data.recommend.forEach(item => {

			// 	arr.push({
			// 		materialCode: item.materialCode,
			// 		qty: item.saleQty - item.scanQty
			// 	})
			// })
			// salesLocation(arr).then(res => {
			// 	tableData.list.forEach(item => {
			// 		res.data.forEach(a => {
			// 			if (item.materialCode == a.materialCode) {
			// 				var str = "";
			// 				if (a.location.length) {

			// 					for (var i = 0; i < a.location.length; i++) {
			// 						str += ((a.location[i].locationCode) + ",")
			// 					}
			// 				}
			// 				item.location = str;
			// 			}
			// 		})

			// 	})
			// 	// data.salesList=res.data

			// 	//这里是用来处理推荐库位的逻辑
			// 	res.data.forEach(h => {
			// 		if (h.location.length) {
			// 			for (var i = 0; i < h.location.length; i++) {
			// 				var lcode = h.location[i].locationCode //库位
			// 				var qty = h.location[i].qty
			// 				if (!data.recommendData.some(m => m.lcode == lcode)) //不存在这个库位
			// 				{
			// 					data.recommendData.push({
			// 						lcode: lcode,
			// 						qty: qty,
			// 						scanQty: 0
			// 					})
			// 				} else {
			// 					for (var j = 0; j < data.recommendData.length; j++) {
			// 						if (data.recommendData[j].lcode == lcode) {
			// 							data.recommendData[j].qty += qty;
			// 						}
			// 					}
			// 				}
			// 			}
			// 		}
			// 	})

			// 	console.log(data.recommendData)
			// 	if (data.recommendData.length) {
			// 		data.recommendData.sort();
			// 		data.recommendCurrent = data.recommendData[0].lcode
			// 	}


			// })
			watcShowscanList(data.barcodeList)
		} else {
			uni.showToast({
				title: res.message,
				icon: 'none'
			})
		}
	})
}
const clickRight = () => {
	navigate({
		url: '/pages/market/stockRemovalReturnRecord'
	})
}

const customBtnFn = (item, index) => {
	data.popupInfo = item;
	// // 点击查看时查询当前物料的推荐库位
	// salesLocation([{
	// 	materialCode: item.materialCode,
	// 	qty: item.saleQty - item.scanQty
	// }]).then(res => {
	// 	// console.log(res.data[0])
	// 	var str = "";
	// 	if (res.data[0]?.location) {

	// 		for (var i = 0; i < res.data[0]?.location.length; i++) {
	// 			str += ((res.data[0]?.location[i].locationCode) + ",")
	// 		}
	// 	}
	// 	data.popupInfo.salesLocation = str.slice(0, str.length - 1);
	// })
	popup.value.open()
}
const closePopup = () => {
	popup.value.close()
}

// 推荐库位点击
const recommendClick = (row, index) => {

	salesLocation([{
		materialCode: row.materialCode,
		qty: row.saleQty - row.scanQty
	}]).then(res => {
		console.log(res.data)
		data.salesList = res.data
		if (res.data[0].location.length) {
			popupRecommend.value.open()
		}
	})


}

const closePopupClick = () => {
	popupRecommend.value.close()
}
</script>

<style scoped lang="scss">
.page-bottom-box {
	z-index: 100;
}

.flex-start {
	align-items: flex-start !important;
}

.specview {
	width: 70%;
	white-space: normal;
	word-break: break-all;
	flex: 1;
}
</style>